package top.zhangjianyong.utils.coding;

/**
 * @program: topzhangjianyongutils
 * @description: 16进制转中文工具类
 * @author: 张建勇
 * @create: 2019-03-14 18:05
 **/
public class HexStrUtil {

    /**
     * * 字符串转换成为16进制(无需Unicode编码)  * @param str  * @return
     */
    public static String str2HexStr(String str) {

        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            // sb.append(' ');
        }
        return sb.toString().trim();

    }

    // 16进制转为字符串

    /**
     * * 16进制直接转换成为字符串(无需Unicode解码)  * @param hexStr  * @return
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }


    /**
     * [0xe9] 转16进制编码
     *
     * @param hexStr
     * @return
     */
    public static String getHexStr(String hexStr) {
        hexStr = hexStr.replaceAll("[\\[\\]]", "");
        hexStr = hexStr.replaceAll("0x", "");

        return hexStr.toUpperCase();
    }

    public static void main(String[] args) {
        String ss = "938D9C88908A9F";
        System.out.println(hexStr2Str(ss));

        String s1 = getHexStr("[0xe9][0x87][0x8d][0xe5][0xa4][0x8d][0xe5][0x87][0xba][0xe6][0xac][0xbe]");
        System.out.println(s1);
        String s2 = hexStr2Str(s1);
        System.out.println(s2);
        String s3 = str2HexStr(s2);
        System.out.println(s3);
    }

}
